package threading;

import javafx.scene.effect.Bloom;

import java.util.Random;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-08-20
 * Time:14:21
 */

/*    给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
    实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
    其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
    最终再汇总两个和, 进行相加
    记录程序的执行时间. */

public class Demo6 {
    public static final int COUNT = 1000_0000;
    private static int sum1 = 0;
    private static int sum2 = 0;
    public static void main(String[] args) {
        int[] arr = new int[(int) COUNT];

        Random random = new Random();
        for (int i = 0; i < COUNT; i++) {
            int num = random.nextInt(100);
            arr[i] = num;
        }
        long beg = System.currentTimeMillis();
        Thread t1 = new Thread(()->{
            for (int j = 0; j < COUNT; j = j+2) {
                sum1 = sum1 + arr[j];
            }
        });
        Thread t2 = new Thread(()-> {
            for (int i = 1; i < COUNT; i = i+2) {
                sum2 = sum2 + arr[i];
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("偶数的和: "+sum1);
        System.out.println("奇数的和: "+sum2);
        System.out.println("耗时: "+(end - beg)+"ms");
    }
}
